//
//  OptionViewController.m
//  Beauty
//
//  Created by Snow on 16/8/29.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "OptionViewController.h"
#import "GXMacro.h"
#import "LoginViewController.h"
#import "OptionTableViewCell.h"
#import "MyInfoViewController.h"
@interface OptionViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, copy) NSString *path;
@end

@implementation OptionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createView];
    // 查询路径
    self.path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    _path = [_path stringByAppendingPathComponent:@"Caches"];
   
    self.view.backgroundColor = [UIColor colorWithRed:0.929 green:0.933 blue:0.922 alpha:1.000];
    self.title = @"设置";
    self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT + 49);
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.110 green:0.102 blue:0.196 alpha:1.000];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.110 green:0.102 blue:0.196 alpha:1.000];
    //tableView
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[OptionTableViewCell class] forCellReuseIdentifier:@"OptionTableViewCell"];
    [_tableView registerClass:[OptionTableViewCell class] forCellReuseIdentifier:@"OptionTableViewCell1"];
    [_tableView registerClass:[OptionTableViewCell class] forCellReuseIdentifier:@"OptionTableViewCell2"];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
}
- (void)createView
{

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 2;
    } else if(section == 2){
        return 5;
    } else {
        return 2;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arrayOfSection = @[@"收货地址", @"清除缓存"];
    NSArray *arrayOfSectionLast = @[@"设计师入驻", @"鼓励一下", @"关于玩艺", @"邀请奖励", @"意见反馈"];
    NSArray *arr = @[@"退出", @""];
    if (indexPath.section == 0) {
        OptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OptionTableViewCell"];
        cell.labelOfOption.text = @"个人资料";
        cell.labelOfOption.textAlignment = 0;
        return cell;
    } else if(indexPath.section == 1) {
        OptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OptionTableViewCell1"];
        cell.labelOfOption.text = arrayOfSection[indexPath.row];
        return cell;
    } else if(indexPath.section == 2){
        OptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OptionTableViewCell2"];
        cell.labelOfOption.text = arrayOfSectionLast[indexPath.row];
        return cell;
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
        cell.textLabel.text = arr[indexPath.row];
        cell.textLabel.textAlignment = 1;
        cell.textLabel.textColor = [UIColor colorWithRed:0.000 green:0.502 blue:0.251 alpha:0.859];
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        MyInfoViewController *my = [[MyInfoViewController alloc] init];
        UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
        self.navigationItem.backBarButtonItem = barItem;
        [self.navigationController pushViewController:my animated:YES];
    }
    if (indexPath.section == 1) {
        //清除缓存
        if (indexPath.row == 1) {
            NSString *string = [NSString stringWithFormat:@"已清除%.2fM", [self floderSizeAtPath:self.path]];
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:string message:@"" preferredStyle:UIAlertControllerStyleAlert];
            // 出现
            [self presentViewController:alertController animated:YES completion:^{
                NSLog(@"presented");
            }];
            // 移除
            [alertController dismissViewControllerAnimated:YES completion:^{
                NSLog(@"dismiss");
            }];
            [self clearAction];
        }
    }
    if (indexPath.section == 3) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定要退出账号?" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        // 添加 AlertAction 事件回调（三种类型：默认，取消，警告）
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //获取UserDefaults单例
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            //移除UserDefaults中存储的用户信息
            [userDefaults removeObjectForKey:@"name"];
            [userDefaults removeObjectForKey:@"password"];
            [userDefaults synchronize];
//            self.tabBarController.tabBar.hidden = YES;
            LoginViewController *login = [[LoginViewController alloc] init];
            [self presentViewController:login animated:YES completion:^{
                self.tabBarController.selectedIndex = 4;
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            // 移除
            [alertController dismissViewControllerAnimated:YES completion:^{
                NSLog(@"dismiss");
            }];
        }];
        
        [alertController addAction:okAction];
        [alertController addAction:cancelAction];
        // 出现
        [self presentViewController:alertController animated:YES completion:^{
            NSLog(@"presented");
        }];
    }
}
//清除缓存
// 计算缓存大小
- (long long)fileSizeAtPath:(NSString *)path {
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        return [[manager attributesOfItemAtPath:path error:nil] fileSize];
    }
    return 0;
}
- (float)floderSizeAtPath:(NSString *)path {
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return 0;
    }else {
        NSEnumerator *enumerator = [[manager subpathsAtPath:path] objectEnumerator];
        NSString *fileName = [NSString string];
        CGFloat floderSize = 0;
        while ((fileName = [enumerator nextObject]) != nil) {
            NSString *absolutPath = [path stringByAppendingPathComponent:fileName];
            floderSize += [self fileSizeAtPath:absolutPath];
        }
        return floderSize/ 1024/ 1024;
    }
    return 0;
}
- (void)clearAction {
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Caches"];
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        NSArray *fileNameArr = [manager subpathsAtPath:path];
        for (NSString *fileName in fileNameArr) {
            NSString *absoltPath = [path stringByAppendingPathComponent:fileName];
            [manager removeItemAtPath:absoltPath error:nil];
        }
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"账号";
    } else if (section == 1) {
    return @"设置";
    } else {
    return @"支持(V : 1.5.1 )";
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 3) {
        return 0;
    } else {
    return 60;
    }
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    CGFloat sectionHeaderHeight = 100;
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY >= 0 && offsetY <= sectionHeaderHeight)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-offsetY, 0, 0, 0);
    }else if (offsetY >= sectionHeaderHeight && offsetY <= scrollView.contentSize.height - scrollView.frame.size.height)
    {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
